﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace Jinndev {

    static class Util {

        public static string GetMD5(string myString) {
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] fromData = Encoding.Unicode.GetBytes(myString);
            byte[] targetData = md5.ComputeHash(fromData);
            string byte2String = null;

            for (int i = 0; i < targetData.Length; i++) {
                byte2String += targetData[i].ToString("x");
            }

            return byte2String;
        }

        public static string GetFileMD5(string filePath) {
            if (!File.Exists(filePath)) {
                return null;
            }
            MD5CryptoServiceProvider md5csp = new MD5CryptoServiceProvider();
            byte[] bytes = null;
            using (FileStream stream = File.OpenRead(filePath)) {
                bytes = md5csp.ComputeHash(stream);
            }

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.Length; i++) {
                sb.Append(bytes[i].ToString("x2"));
            }
            return sb.ToString();
        }

        public static long GetFileSize(string path) {
            return new FileInfo(path).Length;
        }

        public static long GetTotalMs(DateTime dateTime) {
            DateTime dtFrom = new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return (dateTime.Ticks - dtFrom.Ticks) / 10000;
        }

        public static string FindArg(string[] args, params string[] names) {
            for (int i = 0; i < args.Length; i++) {
                foreach (string name in names) {
                    if (args[i] == name && i + 1 < args.Length) {
                        return args[i + 1];
                    }
                }
            }
            return null;
        }

        public static bool HasAnyArgs(string[] args, params string[] names) {
            foreach (string name in names) {
                foreach (string arg in args) {
                    if (name == arg) {
                        return true;
                    }
                }
            }
            return false;
        }

        public static void PrepareFileDir(string file) {
            var dir = new FileInfo(file).Directory;
            if (!dir.Exists) {
                dir.Create();
            }
        }

    }

}
